import re

from plugins import CheckPlugin
from helper import CallProcess, raw2lines, convert_dict_value_to_int
from config import logger

def get_interfaces():
    excludes = ['lo0']
    cmd = '/sbin/ifconfig -l'
    logger.debug('get_interfaces check cmd: %s' % cmd)
    proc = CallProcess(cmd)
    proc()
    return [i for i in proc.stdout.split()
            if i not in excludes]

def get_traffic_statistics(interface):
    cmd = '/usr/bin/netstat -n -i -I %s -b -d' % interface
    logger.debug('%s traffic check cmd: %s' % (interface, cmd))
    pat = re.compile(r'<Link#\d>')
    proc = CallProcess(cmd)
    proc()
    formats = ['name', 'mtu', 'network', 'addr',
               'ipkts', 'ierrs', 'idrop', 'ibytes',
               'opkts', 'oerros', 'obytes', 'coll', 'drop']
    lines = raw2lines(proc.stdout, 1)
    for line in lines:
        values = [v for v in line.split()]
        if pat.search(values[2]):
            return convert_dict_value_to_int(dict(zip(formats, values)))
    return None

class CheckTraffic(CheckPlugin):

    topic = 'traffic'

    def check(self):
        interfaces = get_interfaces()
        for interface in interfaces:
            ret = get_traffic_statistics(interface)
            if ret:
                self.results.append(ret)

